import { observable, action, toJS } from 'mobx';
import { WeaForm, WeaSwitch } from 'comsMobx';
import { WeaLocaleProvider } from 'ecCom';
import { message } from 'antd';

import * as API from '../apis/seat';
let Base64 = ecCom.WeaTools.Base64
const getLabel = WeaLocaleProvider.getLabel;
export default class SeatStore {
  @observable isSingle = false;
  @observable spinning = false;
  @observable seatLayoutSettingVisible = false;
  @observable isVisible_arrngeseat = false;
  @observable unseated_person_hide = false;

  @observable roomId = '';
  @observable meetingId = '';
  @observable seat_isselected = false;
  @observable seat_currentSeatId = '';
  @observable seat_oldHrmId = '';
  @observable seat_parnetDOM = {};
  @observable floatingLayer_before_dom = {};
  @observable floatingLayer_before_seatId = '';
  @observable floatingLayer_before_hrmId = '';
  @observable floatingLayer_end_dom = {};
  @observable floatingLayer_end_seatId = '';
  @observable floatingLayer_end_hrmId = '';
  @observable before_table_number = '';
  @observable end_table_number = '';
  @observable before_seat_label = '';
  @observable end_seat_label = '';

  @observable tableModle = '';
  @observable seatLabelStyle = '';
  @observable defaultRight = { key: 'passageway', value: getLabel('507038', '过道'), backgroundColor: '#fff', map: '_', unavailable: true };
  @observable rightMenu = [this.defaultRight];
  @observable seatConfMap = [];
  @observable has_seatDatas = true; // true: 不为空
  @observable has_seatDatas_content = '';
  @observable oldSeatConfMap = '';
  @observable seatChartsRoot = [];
  @observable typeId = '';
  @observable oneself_seat = '';

  @observable isSetting = false; // 前台设置
  @observable isClear = true;

  @observable isSeatTabstatus = false;

  @observable baseDatas = {
    form: new WeaForm(),
    formData: [],
    editInfo: [],
    squareValue: [],
    circleTables: '',
    circleSeats: '',
  };
  @observable addDatas = {
    addform: new WeaForm(),
    addformData: [],
  };

  @observable save_noticeDatas = {
    save_noticeform: new WeaForm(),
    save_noticeformData: [],
  };

  @observable seatInfo = {
    seatInfoForm: new WeaForm(),
    fieldList: [],
    setinfoLoading: false,
  };

  @observable seatBaseDateChanged = false;
  @observable oldLayoutDel = false;

  @observable retLayoutType = '';
  @observable seatsColordatas = {}

  @observable pre_form = new WeaForm();
  @observable pre_seat_chart = [];
  @observable pre_layoutType = '';
  @observable pre_address = '';
  @observable pre_sortType = '';

  @observable display_fieldList = [];
  @observable display_address = '';
  @observable display_layout = '';
  @observable savedLayoutType = '';
  
  @observable weadialogHeight = ''

  @observable hrmObj = []; 
  @observable hrmObj_byOrganize = [];
  @observable hrmInfo = {
    crmList: [],
    crmNameMap: {},
    hrmList: [],
    hrmNameMap: {},
    depMap: {},
    subMap: {},
    colorList: [],
  };

  @observable arrangeSeatForm = []; // 未排座人员
  @observable arrangeSeatForm_crm = []; // 未排座客户

  @action
  setState = (params, callback) => {
    Object.keys(params).forEach(key => {
      this[key] = params[key];
    });
    typeof (callback) == 'function' && callback();
  }
  getState = (key) => {
    return this[key];
  }
  setBaseDatas = (params) => {
    Object.keys(params).forEach(key => {
      this.baseDatas[key] = params[key];
    });
  }
  setAddDatas = (params) => {
    Object.keys(params).forEach(key => {
      this.addDatas[key] = params[key];
    });
  }

  changeHrm = (newId, oldId, seatid, seatlabel, tableNum) => { 
    let hrm_obj = this.hrmObj;
    let tempArr = [];
    if (parseInt(this.pre_sortType, 10) == 1) { // 按组织结构
      hrm_obj = this.hrmObj_byOrganize;
    }

    hrm_obj && toJS(hrm_obj).map(res => {
      if (res.id == newId) { // 已安排座位
        tempArr.push({
          ...res, isArrange: true, seatId: seatid,
          seatLabel: seatlabel, tableNum: tableNum, roomid: this.roomId
        });
      } else if (res.id == oldId) { // 未安排座位
        tempArr.push({
          ...res, isArrange: false, seatId: '',
          seatLabel: '', tableNum: '', roomid: '',
        });
      } else {
        tempArr.push(res);
      }
    })

    if (parseInt(this.pre_sortType, 10) == 1) { // 按组织结构
      this.hrmObj_byOrganize = tempArr;
    } else {
      this.hrmObj = tempArr;
    }

  }

  getFirstHrmName = () => {
    let arr = toJS(this.hrmObj);
    let res = {}
    if (arr) {
      for (let i in arr) {
        if (!arr[i].isArrange && arr[i].bgcolor && arr[i].bgcolor != '') {
          res = arr[i];
          break;
        }
      }
    }
    return res;
  }

  changHrmColor = (id, bgcolor) => {
    let tempArr = [];
    this.hrmObj && this.hrmObj.map(res => {
      if (res && res.id == id) {
        tempArr.push({ ...res, bgcolor: bgcolor });
      } else {
        tempArr.push(res);
      }
    })
    this.hrmObj = tempArr;
  }

  selectedSeats = (id, oldid, dom) => {
    this.seat_isselected = true;
    this.seat_currentSeatId = id;
    this.seat_oldHrmId = oldid;
    this.seat_parnetDOM = dom;

  }

  getBaseSetDatas = (params, callback) => {
    this.spinning = true;
    API.getBaseSetDatas(params).then(res => {
      this.spinning = false;
      if (res && res.api_status) {
        this.baseDatas.form.initFormFields(toJS(res.data[0]));
        this.rightMenu = [this.defaultRight];
        this.seatConfMap = res.seatConfMap && res.seatConfMap != '' ? res.seatConfMap.split(',') : [];

        res && res.data && res.data[1] && res.data[1][0].items[0].datas && res.data[1][0].items[0].datas.map(res => {
          let rightM = {
            value: Base64.decode(res.colorName.replace('base64_', '')),
            backgroundColor: res.color,
          };
          this.rightMenu.push(rightM);
        })
        this.tableModle = this.baseDatas.form.getFormParams().styleType;
        this.seatLabelStyle = this.baseDatas.form.getFormParams().seatCodeType;
        this.setBaseDatas({
          formData: res.data[0],
          editInfo: res.data[1],
          // squareColumn: this.baseDatas.form.getFormParams().column ,
          // squareRow: this.baseDatas.form.getFormParams().row,
          squareColumn: 10,
          squareRow: 10,
          circleTables: this.baseDatas.form.getFormParams().roundTableNumber,
          circleSeats: this.baseDatas.form.getFormParams().eachTableSeats,
        });

        this.typeId = this.baseDatas.form.getFormParams().typeId;

        if (typeof (callback) == 'function') {
          if (res && res.seatConfMap && res.seatConfMap != '') {
            let map = this.setMap(JSON.parse(res.seatDatas));
            callback(map);
          }
          // res.seatConfMap&&res.seatConfMap!=''&&res.seatConfMap.split(',').length>0 && callback(res.seatConfMap.split(','));
        }
      }
    });
  }
  getSeatLayoutTypeAddData = (params, callback) => {
    this.spinning = true;
    API.getSeatLayoutTypeAddData(params).then(res => {
      this.spinning = false;
      this.addDatas.addformData = toJS(res.fields);
      this.addDatas.addform.initFormFields(toJS(res.fields));
      typeof (callback) == 'function' && callback();
    });
  }

  // 保存并通知
  getSave_notice = (params, callback) => {
    this.spinning = true;
    API.getSave_notice(params).then(res => {
      this.spinning = false;
      this.save_noticeDatas.save_noticeformData = toJS(res.data);
      this.save_noticeDatas.save_noticeform.initFormFields(toJS(res.data));
      typeof (callback) == 'function' && callback();
    });
  }

   // 保存通知方式
   sendSeatMsg = (params, callback) => {
    this.spinning = true;
    API.sendSeatMsg(params).then(res => {
      this.spinning = false;
      if(res && res.ret == 'success') {
        message.success(getLabel('83551','保存成功！') );
        typeof (callback) == 'function' && callback();
      }else{
        message.error(getLabel('84544','保存失败！') );
      }
    });
  }

  addSeatLayoutType = (params) => {
    this.spinning = true;
    API.addSeatLayoutType(params).then(res => {
      this.spinning = false;
      this.getBaseSetDatas({ typeId: res.typeId, roomId: this.roomId });
    });
  }

  saveSeatSetBaseData = (params) => {
    this.spinning = true;
    API.saveSeatSetBaseData(params).then(res => {
      this.spinning = false;
      this.getBaseSetDatas({ typeId: params.typeId, roomId: params.roomId });
    });
  }

  getSeatInfo = (params, callback) => {
    this.spinning = true;
    API.getSeatInfo(params).then(res => {
      this.spinning = false;
      if (res && res.api_status ) {
        this.hrmObj = [];
        this.hrmObj_byOrganize = [];
        this.arrangeSeatForm = [];
        this.arrangeSeatForm_crm = [];
        this.oldSeatConfMap = '';
        this.hrmInfo = {
          crmNameMap: res.crmNameMap ||{},
          hrmNameMap: res.hrmNameMap || {},
          depMap: res.depMap || {},
          subMap: res.subMap || {},
          colorList: res.colorList || []
        };

        this.isVisible_arrngeseat = res.arrangeSeat;
        this.seatBaseDateChanged = res.seatBaseDateChanged;
        this.retLayoutType = res.retLayoutType;
        this.savedLayoutType = res.savedLayoutType;
        this.oldLayoutDel = res.oldLayoutDel;
        this.oldSeatConfMap = res.oldSeatConfMap;

        res && res.seatedInfo instanceof Array && res.seatedInfo.map(res => {
          res = { ...res, isArrange: res.isArrange == 'false' ? false : true, isRemind: res.isRemind == 'false' ? false : true, };
          this.hrmObj.push(res);
        });
        res && res.seatedInfoByOrganize instanceof Array && res.seatedInfoByOrganize.map(res => {
          res = { ...res, isArrange: res.isArrange == 'false' ? false : true, isRemind: res.isRemind == 'false' ? false : true, };
          this.hrmObj_byOrganize.push(res);
        });
        if (res.fieldList) {
          this.seatInfo.seatInfoForm.initFormFields(res.fieldList);
          this.pre_form.initFormFields(res.fieldList);
          res.fieldList[0] && res.fieldList[0].items && res.fieldList[0].items.map(res => {
            if(res && res.domkey[0] === "seatSymbol") { // 座位图例
              this.pre_seat_chart =  res.options;
            }else if (res.domkey[0] === 'unseatedCrm') { // 未排座客户
              this.arrangeSeatForm_crm.push(res);
            }else if(res.domkey[0] === 'sortType' || res.domkey[0] === 'unseatedMember') { // 未排座人员
              this.arrangeSeatForm.push(res);
            }
          })
        }
        this.seatInfo.fieldList = res.fieldList;
        this.tableModle = res.styleType;
        this.baseDatas.circleTables = res.roundTableNumber;
        this.oneself_seat = res.selfId;
        this.pre_layoutType = this.seatInfo.seatInfoForm.getFormParams().layoutType;
        this.pre_address = this.seatInfo.seatInfoForm.getFormParams().address;
        this.roomId = this.seatInfo.seatInfoForm.getFormParams().address;
        this.pre_sortType = this.pre_form.getFormParams().sortType;
        
        if (typeof (callback) == 'function') {
          if (res.seatDatas && res.seatDatas != '') {
            let map = this.setMap(JSON.parse(res.seatDatas));
            callback(map, this.hrmInfo.hrmNameMap);
          } else {
            if (res.seatConfMap && res.seatConfMap != '') {
              let map = this.setMap(JSON.parse(res.seatConfMap));
              
              this.has_seatDatas = false;
              this.has_seatDatas_content = res.seatConfMap;
              callback(map,  this.hrmInfo.hrmNameMap);
            }
          }
        }
      }
    });
  }

  setMap = (map) => {
    let arr = [];
    let t_arr = [];
    map instanceof Array && map.forEach(item => {
      item && item.forEach((res, i) => {
        let t = [];
        res && res.forEach(r => {
          if (r.isPassageway) {
            t.push({ ...r, map: '_', bgcolor: '' });
          } else {
            t.push(r)
          }
        });
        t_arr.push(t);
      });
    })
    arr.push(t_arr);
    return arr;
  }

  getSeatInfo_pre = (params, callback) => {
    this.spinning = true;
    API.getSeatInfo(params).then(res => {
      this.spinning = false;
      if (res && res.api_status) {
        this.hrmObj = [];
        this.hrmObj_byOrganize = [];
        this.hrmInfo.hrmNameMap = {};
        let display_form = new WeaForm();
        res && res.seatedInfo instanceof Array && res.seatedInfo.map(res => {
          res = { ...res, isArrange: res.isArrange == 'false' ? false : true, isRemind: res.isRemind == 'false' ? false : true, };
          this.hrmObj.push(res);
          this.hrmInfo.hrmNameMap[res.id] = res.name; 
        });

        res && res.seatedInfoByOrganize instanceof Array && res.seatedInfoByOrganize.map(res => {
          res = { ...res, isArrange: res.isArrange == 'false' ? false : true, isRemind: res.isRemind == 'false' ? false : true, };
          this.hrmObj_byOrganize.push(res);
        });

        res && display_form.initFormFields([res.fieldList[0]]);
        this.display_address = display_form.getFormParams().address;
        // this.display_layout = display_form.getFormParams().layoutType;
        this.tableModle = res.styleType;
        this.display_fieldList = res.fieldList;
        this.oneself_seat = res.selfId;
        if (typeof (callback) == 'function') {
          if (res.seatDatas && res.seatDatas != '') {
            let map = this.setMap(JSON.parse(res.seatDatas));
            callback(map, this.hrmInfo.hrmNameMap);
          } else {
            let map = this.setMap(JSON.parse(res.seatConfMap));

            res.seatConfMap && res.seatConfMap != '' && callback(map, this.hrmInfo.hrmNameMap);
          }
        }
      }
    });
  }

  saveSeatInfo = (params, callback) => {
    this.spinning = true;
    API.saveSeatInfo(params).then(res => {
      this.spinning = false;
      if (res && res.ret == 'success' && typeof (callback) == 'function') {
        callback()
      }
    });
  }

  // 更新座位布局
  delMeetingSeat = (params, callback) => {
    API.delMeetingSeat(params).then(res => {
      if (res && res.ret == 'success' && typeof (callback) == 'function') {
        callback()
      }
    });
  }

   // 判断是否显示排座信息tab页
  getSeatTabStatus = (params) => {
    API.getSeatTabStatus(params).then(res => {
      if (res && res.ret == 'success' ) {
        this.isSeatTabstatus = res.showSeatTab;
      }
    });
  }

}

